<template>
  <div class="invoice-detail-page">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <van-loading color="#1989fa" size="24px">加载中...</van-loading>
    </div>
    
    <!-- 发票信息卡片 -->
    <template v-else>
      <div class="invoice-card">
        <div class="invoice-header">
          <div class="status-tag">
            <van-tag :type="getStatusType(invoice.status)" size="medium">
              {{ getStatusText(invoice.status) }}
            </van-tag>
          </div>
          <div class="invoice-number">
            <span class="label">发票号码：</span>
            <span class="value">{{ invoice.number }}</span>
          </div>
          <div class="invoice-code">
            <span class="label">发票代码：</span>
            <span class="value">{{ invoice.code }}</span>
          </div>
        </div>
        
        <div class="invoice-image" @click="previewImage">
          <img :src="invoice.imageUrl" alt="发票图片" />
          <div class="image-overlay">
            <van-icon name="search" size="24" color="#fff" />
            <span>点击查看大图</span>
          </div>
        </div>
        
        <div class="invoice-info">
          <van-cell-group inset>
            <van-cell title="发票类型" :value="getTypeName(invoice.type)" />
            <van-cell title="开票日期" :value="invoice.date" />
            <van-cell title="销售方" :value="invoice.seller" />
            <van-cell title="购买方" :value="invoice.buyer" />
            <van-cell title="发票金额" :value="`¥${formatAmount(invoice.amount)}`" />
            <van-cell title="税额" :value="`¥${formatAmount(invoice.tax)}`" />
            <van-cell title="价税合计" :value="`¥${formatAmount(invoice.totalAmount)}`" class="total-amount" />
          </van-cell-group>
        </div>
      </div>
      
      <!-- 商品明细 -->
      <div class="goods-section">
        <div class="section-title">
          <span>商品明细</span>
        </div>
        <van-cell-group inset>
          <van-cell v-for="(item, index) in invoice.items" :key="index">
            <template #title>
              <div class="goods-item">
                <div class="goods-name">{{ item.name }}</div>
                <div class="goods-spec">{{ item.spec }}</div>
                <div class="goods-row">
                  <span class="goods-quantity">{{ item.quantity }}{{ item.unit }}</span>
                  <span class="goods-price">¥{{ formatAmount(item.price) }}</span>
                </div>
                <div class="goods-amount">¥{{ formatAmount(item.amount) }}</div>
              </div>
            </template>
          </van-cell>
        </van-cell-group>
      </div>
      
      <!-- 发票信息 -->
      <div class="additional-info">
        <div class="section-title">
          <span>其他信息</span>
        </div>
        <van-cell-group inset>
          <van-cell title="上传时间" :value="invoice.uploadTime" />
          <van-cell title="关联报销" :value="invoice.reimbursement || '未关联'" />
          <van-cell title="归属部门" :value="invoice.department" />
        </van-cell-group>
      </div>
      
      <!-- 操作按钮组 -->
      <div class="action-buttons">
        <van-button 
          v-if="invoice.status === 'pending'" 
          icon="success" 
          type="primary" 
          block 
          @click="verifyInvoice"
        >
          验证发票
        </van-button>
        <van-button 
          v-if="invoice.status !== 'invalid'" 
          icon="delete-o" 
          type="danger" 
          block 
          @click="showInvalidDialog"
        >
          作废发票
        </van-button>
        <van-button 
          icon="share-o" 
          plain 
          block 
          @click="shareInvoice"
        >
          分享发票
        </van-button>
      </div>
    </template>
    
    <!-- 作废确认弹窗 -->
    <CustomPopup
      v-model:show="showDialog"
      title="作废发票"
      @close="cancelInvalidate"
    >
      <div class="dialog-content">
        <p>确定要将此发票标记为作废吗？</p>
        <p class="dialog-warning">此操作不可撤销！</p>
        <van-field
          v-model="invalidReason"
          label="作废原因"
          placeholder="请输入作废原因"
          :rules="[{ required: true, message: '请填写作废原因' }]"
        />
      </div>
      
      <template #footer>
        <div class="popup-footer-buttons">
          <van-button plain type="default" @click="cancelInvalidate">取消</van-button>
          <van-button type="primary" @click="invalidateInvoice">确认</van-button>
        </div>
      </template>
    </CustomPopup>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { 
  NavBar, Loading, Tag, Cell, CellGroup, Icon,
  Button, Dialog, Field, Toast, ImagePreview
} from 'vant'
import CustomPopup from '@/components/CustomPopup.vue'

export default {
  name: 'InvoiceDetail',
  components: {
    vanNavBar: NavBar,
    vanLoading: Loading,
    vanTag: Tag,
    vanCell: Cell,
    vanCellGroup: CellGroup,
    vanIcon: Icon,
    vanButton: Button,
    vanDialog: Dialog,
    vanField: Field,
    CustomPopup
  },
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  setup(props) {
    const router = useRouter()
    const route = useRoute()
    const store = useStore()
    
    // 加载状态
    const loading = ref(true)
    
    // 发票数据
    const invoice = ref({})
    
    // 作废对话框
    const showDialog = ref(false)
    const invalidReason = ref('')
    
    // 获取发票类型名称
    const getTypeName = (type) => {
      const typeMap = {
        'vat-special': '增值税专票',
        'vat-normal': '增值税普票',
        'electronic': '电子发票',
        'other': '其他票据'
      }
      return typeMap[type] || type
    }
    
    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        'verified': 'success',
        'pending': 'warning',
        'used': 'primary',
        'invalid': 'danger'
      }
      return statusMap[status] || 'default'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'verified': '已验证',
        'pending': '待验证',
        'used': '已使用',
        'invalid': '已作废'
      }
      return statusMap[status] || status
    }
    
    // 格式化金额
    const formatAmount = (amount) => {
      return parseFloat(amount).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
    }
    
    // 返回上一页
    const onBackClick = () => {
      router.back()
    }
    
    // 获取发票详情
    const fetchInvoiceDetail = () => {
      loading.value = true
      
      // 模拟API请求
      setTimeout(() => {
        invoice.value = {
          id: props.id,
          number: '31764609',
          code: '044001900311',
          type: 'vat-special',
          status: 'verified',
          date: '2023-10-15',
          seller: '某科技有限公司',
          buyer: '某企业集团有限公司',
          amount: 1100.00,
          tax: 180.00,
          totalAmount: 1280.00,
          imageUrl: 'https://img.yzcdn.cn/vant/cat.jpeg', // 示例图片
          uploadTime: '2023-10-16 14:30',
          reimbursement: '报销单2023-R001',
          department: '研发部',
          items: [
            {
              name: '笔记本电脑',
              spec: 'Model-X Pro',
              quantity: 1,
              unit: '台',
              price: 1100.00,
              amount: 1100.00
            }
          ]
        }
        
        loading.value = false
      }, 1000)
    }
    
    // 预览图片
    const previewImage = () => {
      ImagePreview([invoice.value.imageUrl])
    }
    
    // 显示作废对话框
    const showInvalidDialog = () => {
      showDialog.value = true
    }
    
    // 验证发票
    const verifyInvoice = () => {
      Toast.loading({
        message: '验证中...',
        forbidClick: true,
      })
      
      // 模拟验证过程
      setTimeout(() => {
        Toast.success('发票验证成功')
        invoice.value.status = 'verified'
      }, 1500)
    }
    
    // 取消作废操作
    const cancelInvalidate = () => {
      invalidReason.value = '';
      showDialog.value = false;
    }
    
    // 作废发票
    const invalidateInvoice = () => {
      if (!invalidReason.value) {
        Toast('请输入作废原因')
        return
      }
      
      Toast.loading({
        message: '处理中...',
        forbidClick: true,
      })
      
      // 模拟API请求
      setTimeout(() => {
        Toast.success('发票已作废')
        invoice.value.status = 'invalid'
        invalidReason.value = ''
        showDialog.value = false
      }, 1000)
    }
    
    // 分享发票
    const shareInvoice = () => {
      Toast('分享功能开发中')
    }
    
    // 初始化
    onMounted(() => {
      fetchInvoiceDetail()
    })
    
    return {
      loading,
      invoice,
      showDialog,
      invalidReason,
      getTypeName,
      getStatusType,
      getStatusText,
      formatAmount,
      onBackClick,
      previewImage,
      showInvalidDialog,
      verifyInvoice,
      invalidateInvoice,
      cancelInvalidate,
      shareInvoice
    }
  }
}
</script>

<style scoped>
.invoice-detail-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 24px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
}

.invoice-card {
  margin: 12px;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.invoice-header {
  padding: 16px;
  border-bottom: 1px solid #f2f3f5;
  position: relative;
}

.status-tag {
  position: absolute;
  right: 16px;
  top: 16px;
}

.invoice-number, .invoice-code {
  margin-bottom: 8px;
}

.label {
  color: #646566;
  font-size: 14px;
}

.value {
  font-weight: 500;
  margin-left: 4px;
}

.invoice-image {
  position: relative;
  height: 180px;
  overflow: hidden;
}

.invoice-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-overlay span {
  color: #fff;
  margin-top: 8px;
  font-size: 14px;
}

.invoice-image:hover .image-overlay {
  opacity: 1;
}

.invoice-info {
  padding: 12px 0;
}

.total-amount {
  font-weight: bold;
  color: #ff976a;
}

.total-amount :deep(.van-cell__value) {
  color: #ff976a;
}

.goods-section,
.additional-info {
  margin-top: 16px;
}

.section-title {
  padding: 0 16px;
  margin-bottom: 8px;
  font-size: 15px;
  font-weight: 500;
  color: #323233;
}

.goods-item {
  padding: 8px 0;
}

.goods-name {
  font-weight: 500;
  font-size: 14px;
  margin-bottom: 4px;
}

.goods-spec {
  font-size: 12px;
  color: #969799;
  margin-bottom: 8px;
}

.goods-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
}

.goods-quantity {
  font-size: 13px;
  color: #646566;
}

.goods-price {
  font-size: 13px;
  color: #646566;
}

.goods-amount {
  text-align: right;
  font-size: 14px;
  font-weight: 500;
  color: #ff976a;
}

.action-buttons {
  margin: 24px 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.dialog-content {
  padding: 24px 16px 0;
}

.dialog-warning {
  color: #ee0a24;
  font-size: 14px;
  margin-bottom: 16px;
}

/* 暗黑模式适配 */
@media (prefers-color-scheme: dark) {
  .invoice-card,
  .invoice-info .van-cell-group,
  .goods-section .van-cell-group,
  .additional-info .van-cell-group {
    background-color: #1c1c1e;
  }
  
  .invoice-header {
    border-bottom-color: #2c2c2e;
  }
  
  .section-title {
    color: #f5f5f5;
  }
  
  .goods-name {
    color: #f5f5f5;
  }
}

/* 添加弹窗按钮样式 */
.popup-footer-buttons {
  display: flex;
  gap: 12px;
}

.popup-footer-buttons .van-button {
  flex: 1;
}
</style> 